package com.example.fengyungo.controller.user;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.example.fengyungo.constant.PayConstant;
import com.example.fengyungo.domain.dto.DriverOrderDTO;
import com.example.fengyungo.domain.entity.Order;
import com.example.fengyungo.domain.pojo.OrderResult;
import com.example.fengyungo.result.Result;
import com.example.fengyungo.service.OrderResultService;
import com.example.fengyungo.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 徐
 */
@Slf4j
@RestController
@RequestMapping("/user/alipay")
public class PayController {

    // 获取配置文件中的配置信息
    /**
     * 支付宝公钥
     */
    @Value("${alipay.public-key}")
    private String publicKey;

    /**
     * 签名方式
     */
    @Value("${alipay.sign-type}")
    private String signType;

    /**
     * 字符编码格式
     */
    @Value("${alipay.charset}")
    private String charset;

    @Autowired
    private OrderResultService orderResultService;

    @Autowired
    private PayService payService;

    /**
     * 用户向平台支付
     * @param order Order订单详情
     * @return Result
     * @throws AlipayApiException AlipayApiException
     */
    @PostMapping
    public Result pay(@RequestBody Order order) throws AlipayApiException {
        AlipayTradeAppPayResponse response = payService.getOrderStr(order);

        String orderStr = response.getBody();
        if (response.isSuccess()) {
            log.info("调用成功");
            return Result.success(orderStr);
        } else {
            log.error("调用失败");
            return Result.error(response.getMsg());
        }
    }

    /**
     * 支付宝支付回调
     * @param request HttpServletRequest
     * @return Result
     * @throws AlipayApiException AlipayApiException
     */
    @PostMapping("/notify")
    public Result notify(HttpServletRequest request) throws AlipayApiException {
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String paramValue = request.getParameter(paramName);
            params.put(paramName, paramValue);
        }
        // 验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, publicKey, charset, signType);
        if (signVerified) {
            // 处理支付结果
            String tradeStatus = params.get("trade_status");
            String outTradeNo = params.get("out_trade_no");
            String tradeNo = params.get("trade_no");
            String totalAmount = params.get("total_amount");
            // TODO: 处理支付结果
            log.info("tradeStatus="+tradeStatus);
            log.info("outTradeNo="+outTradeNo);
            log.info("tradeNo="+tradeNo);
            log.info("totalAmount="+totalAmount);

            // 如果支付成功
            if (tradeStatus.equals("TRADE_SUCCESS")) {
                OrderResult orderResult = OrderResult.builder()
                        .tradeStatus(tradeStatus)
                        .outTradeNo(outTradeNo)
                        .tradeNo(tradeNo)
                        .totalAmount(totalAmount)
                        .build();
                orderResultService.addOrderResult(orderResult);
            }
            return Result.success();
        } else {
            return Result.error(PayConstant.SIGN_ERROR);
        }
    }

    /**
     * 平台退款给用户
     * @param order Order
     * @return Result
     * @throws AlipayApiException AlipayApiException
     */
    @PostMapping("/refund")
    public Result refund(@RequestBody Order order) throws AlipayApiException {
        AlipayTradeRefundResponse response = payService.refund(order);

        if(response.isSuccess()){
            log.info("调用成功");
            return Result.success();
        } else {
            log.error("调用失败");
            log.error(response.getMsg());
            return Result.error(response.getMsg());
        }
    }

    /**
     * 平台转账给司机
     * @param driverOrderDTO 司机账号信息
     * @return Result
     */
    @PostMapping("/driver")
    public Result payToDriver(@RequestBody DriverOrderDTO driverOrderDTO) throws AlipayApiException {
        AlipayFundTransUniTransferResponse response = payService.payToDriver(driverOrderDTO);

        if (response.isSuccess()) {
            log.info("调用成功");
            return Result.success();
        } else {
            log.error("调用失败");
            return Result.error(response.getMsg());
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
    }
}
